package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/live/api/request"
	"zg3/live/internal/dao"
	"zg3/live/internal/model"
)

func AddUserComment(c *gin.Context) {
	var req request.AddUserCommentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	comment := model.UserComments{
		LiveId:  req.LiveId,
		UserId:  c.GetUint("userId"),
		Content: req.Content,
	}
	if !dao.Create(&comment) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "评论失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "评论成功",
		"data": comment,
	})
}

func QueryUserComment(c *gin.Context) {
	var req request.QueryUserCommentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	liveContents := dao.FindLiveContent(req.LiveId)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询直播间评论成功",
		"data": liveContents,
	})
}

func UpdateUserComment(c *gin.Context) {
	var req request.UpdateUserCommentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var comment model.UserComments
	dao.FindId(req.CommentId, &comment)
	if comment.Id == 0 || comment.UserId != c.GetUint("userId") {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "修改失败",
			"data": nil,
		})
		return
	}
	comment.Content = req.Content
	if !dao.Update(&comment) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "修改评论内容失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "修改评论成功",
		"data": comment,
	})
}

func RemoveUserComment(c *gin.Context) {
	var req request.RemoveUserCommentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var comment model.UserComments
	dao.FindId(req.CommentId, &comment)
	if comment.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该评论不存在",
			"data": nil,
		})
		return
	}
	if comment.UserId != c.GetUint("userId") {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "没有权限删除此评论",
			"data": nil,
		})
		return
	}
	if !dao.Remove(&comment) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除成功",
		"data": true,
	})
}
